import { CommonToast } from 'src/utils/ToastUtil'
import { BackHandler } from 'react-native'
import { IS_ANDROID } from 'src/utils/ScreenUtil'
import { enableAndroidDoubleBackExit } from 'src/utils/ConfigUtil'

const hardwareBackPress = 'hardwareBackPress'

/**
 * 安卓退出应用
 */
function doublePressExitApp () {
  if (enableAndroidDoubleBackExit) {
    if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
      // 最近2秒内按过back键，可以退出应用。
      return false
    }

    this.lastBackPressed = Date.now()
    CommonToast('再按一次退出应用')
    return true
  } else {
    return false
  }
}

/**
 * 安卓返回按钮的监控
 * @private
 */
function hardwareBackPressListener (listenerCallback) {
  if (IS_ANDROID) {
    BackHandler.addEventListener(hardwareBackPress, listenerCallback)
  }
}

/**
 * 移除返回按钮的监控
 * @private
 */
function removeHardwareBackPress (listenerCallback) {
  if (IS_ANDROID) {
    BackHandler.removeEventListener(hardwareBackPress, listenerCallback)
  }
}

export default {
  doublePressExitApp,
  hardwareBackPressListener,
  removeHardwareBackPress
}
